﻿using CommandListPanel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Workbench
{
    /// <summary>
    /// WorkbenchPanel.xaml 的交互逻辑
    /// </summary>
    public partial class WorkbenchPanel : UserControl
    {

        public string Api = "";
        public string Token = "";
        public JObject UserInfor = null;
        public WorkbenchPanel(string api, string token, JObject userinfor)
        {
            Api= api;
            Token = token;
            UserInfor = userinfor;
            InitializeComponent();
            _ = getCommandList();
        }


        private void addtest_Click(object sender, RoutedEventArgs e)
        {
            

        }




        /// <summary>
        /// 从api获取命令列表
        /// </summary>
        /// <returns></returns>
         async Task getCommandList()
        {
            try
            {
                // 假设这是您从某处获得的有效token

                // 设置API的URL
                string url = Api+"/commands";  // 请根据实际情况修改URL
                HttpClient client = new HttpClient();
                // 添加Authorization头 (假设是Bearer token)
                client.DefaultRequestHeaders.Add("Authorization", Token);

                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(url);

                // 确保请求成功
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();

                // 打印响应内容到控制台
                JArray jArray = JArray.Parse(responseBody);
                commandListHandle(jArray);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }


        //命令列表处理:分类,排序,添加
        /// <summary>
        /// 命令列表处理:分类,排序,添加
        /// </summary>
        /// <param name="clist"></param>
        void commandListHandle(JArray clist1) {


            // 使用OrderBy方法对clist按ctype进行排序
            var clist = clist1.OrderBy(c => c["ctype"].ToString()).ToList();



            //使用索引器访问clist中的元素
            Dictionary<string, int> commandList= new Dictionary<string, int>();
            string ctype = "";
            int commandListCount = 0;
            for (int i = 0; i < clist.Count; i++)
            {
                string ctype1 = clist[i]["ctype"].ToString();
                string content = HexsToStr(clist[i]["content"].ToString(), Encoding.Default);
                JObject keyValuePairs = (JObject)JsonConvert.DeserializeObject(content);
                if (!keyValuePairs.ContainsKey("fun_type") || !keyValuePairs.ContainsKey("othername"))
                {
                    continue;
                }



                if (ctype != clist[i]["ctype"].ToString())
                {
                    ctype = clist[i]["ctype"].ToString();
                    scriptMake.c1 = ctype == "wb" ? "#108ee9" : ctype == "ml" ? "#9966FF" : ctype == "mw" ? "#15B244" : "#666666";
                    scriptMake.c2 = ctype == "wb" ? "#77C0F4" : ctype == "ml" ? "#B786FF" : ctype == "mw" ? "#4AB36B" : "#dddddd";
                    scriptMake.c3 = ctype == "wb" ? "#4aadf4" : ctype == "ml" ? "#CEAAFF" : ctype == "mw" ? "#5CB280" : "#999999";
                    commandList.Add(checkTypeString(ctype), commandListCount);
                    Console.WriteLine(">>>>>>>>>>>>>>..." + commandListCount);
                    scriptMake.ScriptCommandsAddTitle(checkTypeString(ctype));
                }


                TypedJobject typedJobject = new TypedJobject();
                typedJobject.Type = clist[i]["ctype"].ToString();
                typedJobject.Data = keyValuePairs;
                scriptMake.CommandControlList.Add(typedJobject);
                scriptMake.CommandControlList.addJobject += ScriptCommands_addJobject;
                commandListCount++;
            }

            scriptMake.ScriptDateList.ScriptList.Clear();
            //显示分类
            foreach (var x  in commandList)
            {
                string ccolor = ctype == "wb" ? "#108ee9" : ctype == "ml" ? "#9966FF" : ctype == "mw" ? "#15B244" : "#666666";
                Console.WriteLine("<<<<<<>>>>>>"+ ccolor);
                scriptMake.ScriptDateList.ScriptList.Add(new CommandType() { Name=x.Key,Commandmodel= scriptMake.CommandModelList[x.Value],
                    BackgroundColor= new SolidColorBrush((Color)ColorConverter.ConvertFromString(
                        x.Key == "网页" ? "#108ee9" : x.Key == "手机" ? "#9966FF" : x.Key == "通用" ? "#15B244" : "#666666"
                        ))
            });
                //Console.WriteLine(x.Value.Name);

            }

            Console.WriteLine("命令类型有多少种?...."+commandList.Count);
        }

        string checkTypeString(string x) {
        

            return x == "ml" ? "手机" : x == "wb" ? "网页" : x == "mw" ? "通用" : "";
        }


        private void ScriptCommands_addJobject(TypedJobject x)
        {
            
        }



        /// <summary>
        /// 16进制字符串转 普通字符串
        /// </summary>
        /// <param name="Hexs"></param>
        /// <returns></returns>
        public string HexsToStr(string Hexs, Encoding ec)
        {
            try
            {
                if (Hexs.Length % 2 == 1 || Hexs.Length == 0)
                {
                    return null;
                }//判断是否合适有效的输入字符串
                string[] chars = new string[Hexs.Length / 2];//根据输入字符串,定义数组长度
                for (int cid = 0; cid < chars.Length; cid++)
                {
                    chars[cid] = Hexs.Substring(cid * 2, 2);
                }//把数组,第2个字符一组侵害为字符数组

                byte[] returnBytes = new byte[chars.Length];//转化为字节数组
                for (int i = 0; i < chars.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(chars[i], 16);
                }//根据字符编码,逐个把byte转回为字符
                return ec.GetString(returnBytes);

            }
            catch (Exception)
            {
                return null;
            }
        }




        /// <summary>
        /// 普通字符串转 16进制字符串
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public string StrToHexs(string Str, Encoding ec)
        {
            try
            {
                byte[] bts = ec.GetBytes(Str);//把普通字符串,转化为字节数组
                StringBuilder builder = new StringBuilder();//可变化字符串
                for (int i = 0; i < bts.Length; i++)
                {
                    builder.Append(string.Format("{0:X2}", bts[i]));
                }//遍历,把字节数组转化为字符形态
                return builder.ToString().Trim();

            }
            catch (Exception)
            {
                return null;
            }
        }

    }
}
